﻿using Microsoft.Win32.TaskScheduler;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace schtasks2
{
    /// <summary>
    /// 任务计划辅助类
    /// </summary>
    public class TaskServiceHelper
    {
        public static Trigger[] FromJsonFormat(string json)
        {
            List<Trigger> listTriggers = new List<Trigger>();
            if (!string.IsNullOrEmpty(json))
            {
                JObject contentTrigger = JObject.Parse(json);
                if (contentTrigger.ContainsKey("CalendarTrigger"))
                {
                    DailyTrigger trigger1 = JsonConvert.DeserializeObject<DailyTrigger>(contentTrigger.GetValue("CalendarTrigger").ToString());
                    listTriggers.Add(trigger1);
                }
                else if (contentTrigger.ContainsKey("TimeTrigger"))
                {
                    TimeTrigger trigger1 = JsonConvert.DeserializeObject<TimeTrigger>(contentTrigger.GetValue("TimeTrigger").ToString());
                    listTriggers.Add(trigger1);
                }
                else if (contentTrigger.ContainsKey("WeeklyTrigger"))
                {
                    WeeklyTrigger trigger1 = JsonConvert.DeserializeObject<WeeklyTrigger>(contentTrigger.GetValue("WeeklyTrigger").ToString());
                    listTriggers.Add(trigger1);
                }
                else if (contentTrigger.ContainsKey("MonthlyDOWTrigger"))
                {
                    MonthlyDOWTrigger trigger1 = JsonConvert.DeserializeObject<MonthlyDOWTrigger>(contentTrigger.GetValue("MonthlyDOWTrigger").ToString());
                    listTriggers.Add(trigger1);
                }
                else if (contentTrigger.ContainsKey("MonthlyTrigger"))
                {
                    MonthlyTrigger trigger1 = JsonConvert.DeserializeObject<MonthlyTrigger>(contentTrigger.GetValue("MonthlyTrigger").ToString());
                    listTriggers.Add(trigger1);
                }
                else if (contentTrigger.ContainsKey("BootTrigger"))
                {
                    BootTrigger trigger1 = JsonConvert.DeserializeObject<BootTrigger>(contentTrigger.GetValue("BootTrigger").ToString());
                    listTriggers.Add(trigger1);
                }
                else if (contentTrigger.ContainsKey("LogonTrigger"))
                {
                    LogonTrigger trigger1 = JsonConvert.DeserializeObject<LogonTrigger>(contentTrigger.GetValue("LogonTrigger").ToString());
                    listTriggers.Add(trigger1);
                }
                else if (contentTrigger.ContainsKey("IdleTrigger"))
                {
                    IdleTrigger trigger1 = JsonConvert.DeserializeObject<IdleTrigger>(contentTrigger.GetValue("IdleTrigger").ToString());
                    listTriggers.Add(trigger1);
                }
                else if (contentTrigger.ContainsKey("EventTrigger"))
                {
                    EventTrigger trigger1 = JsonConvert.DeserializeObject<EventTrigger>(contentTrigger.GetValue("EventTrigger").ToString());
                    listTriggers.Add(trigger1);
                }
                else if (contentTrigger.ContainsKey("SessionStateChangeTrigger"))
                {
                    SessionStateChangeTrigger trigger1 = JsonConvert.DeserializeObject<SessionStateChangeTrigger>(contentTrigger.GetValue("SessionStateChangeTrigger").ToString());
                    listTriggers.Add(trigger1);
                }
                else if (contentTrigger.ContainsKey("RegistrationTrigger"))
                {
                    RegistrationTrigger trigger1 = JsonConvert.DeserializeObject<RegistrationTrigger>(contentTrigger.GetValue("RegistrationTrigger").ToString());
                    listTriggers.Add(trigger1);
                }
                else if (contentTrigger.ContainsKey("Triggers"))
                {
                    JObject ct = JObject.Parse(contentTrigger.GetValue("Triggers").ToString());
                    if (ct.ContainsKey("CalendarTrigger"))
                    {
                        DailyTrigger trigger2 = JsonConvert.DeserializeObject<DailyTrigger>(ct.GetValue("CalendarTrigger").ToString());
                        listTriggers.Add(trigger2);
                    }
                }
                else
                {
                    Trigger trigger1 = JsonConvert.DeserializeObject<Trigger>(json);
                    listTriggers.Add(trigger1);
                }
            }
            return listTriggers.ToArray();
        }

        public static Trigger[] FromCronFormat(string cron)
        {
            return Trigger.FromCronFormat(cron);
        }

        public static TaskCollection AllTasks()
        {
            return new TaskService().RootFolder.Tasks;
        }

        public static bool AddTask(
            string taskName,
            string taskDesc,
            string taskrun,
            string arguments,
            string workingDirectory,
            string username,
            string password,
            string schedule,
            bool it,
            string rl,
            bool f,
            Trigger[] listTriggers)
        {
            bool result = false;
            TaskService taskService = new TaskService();
            TaskDefinition taskDefinition = taskService.NewTask();
            taskDefinition.RegistrationInfo.Description = taskDesc;
            if (!String.IsNullOrEmpty(schedule) && schedule.ToUpper() == "ONSTART")
            {
                taskDefinition.Triggers.Add(new BootTrigger
                {
                    Delay = TimeSpan.FromMinutes(5), // 可选：设置延迟时间
                    Enabled = true
                });
            }
            else
            {
                if (listTriggers != null && listTriggers.Any())
                {
                    foreach (Trigger trigger in listTriggers)
                    {
                        taskDefinition.Triggers.Add(trigger);
                    }
                }
                else
                {

                    taskDefinition.Triggers.Clear();
                }
            }
            taskDefinition.Settings.AllowDemandStart = true;
            taskDefinition.Settings.AllowHardTerminate = false;
            taskDefinition.Settings.DisallowStartIfOnBatteries = false;
            taskDefinition.Settings.StopIfGoingOnBatteries = false;
            taskDefinition.Settings.ExecutionTimeLimit = TimeSpan.Zero;
            taskDefinition.Settings.DisallowStartOnRemoteAppSession = true;
            taskDefinition.Settings.UseUnifiedSchedulingEngine = false;
            taskDefinition.Settings.MultipleInstances = 0;
            taskDefinition.Settings.IdleSettings.StopOnIdleEnd = true;
            taskDefinition.Settings.IdleSettings.RestartOnIdle = false;
            taskDefinition.Settings.RunOnlyIfIdle = false;
            // 只有在网络连接时才运行
            taskDefinition.Settings.RunOnlyIfNetworkAvailable = false;
            // 不运行远程控制运行
            taskDefinition.Settings.DisallowStartOnRemoteAppSession = false;
            taskDefinition.Settings.UseUnifiedSchedulingEngine = true;
            // 唤醒计算机运行此任务
            taskDefinition.Settings.WakeToRun = true;
            taskDefinition.Actions.Add(new ExecAction(taskrun, arguments, workingDirectory));
            if (!String.IsNullOrEmpty(rl) && rl.ToUpper() == "HIGHEST")
            {
                taskDefinition.Principal.RunLevel = TaskRunLevel.Highest;
            }
            else
            {
                taskDefinition.Principal.RunLevel = TaskRunLevel.LUA;
            }
            Microsoft.Win32.TaskScheduler.Task task = null;
            if (!String.IsNullOrEmpty(username)
                && (username.ToUpper() == "SYSTEM"
                || username.ToUpper() == "NT AUTHORITY\\SYSTEM"))
            {
                taskDefinition.Principal.LogonType = TaskLogonType.ServiceAccount;
                taskDefinition.Principal.UserId = "NT AUTHORITY\\SYSTEM";
                task = taskService.RootFolder.RegisterTaskDefinition(
                    taskName,
                    taskDefinition,
                    TaskCreation.CreateOrUpdate,
                    null,
                    null,
                    logonType: TaskLogonType.ServiceAccount);
            }
            else
            {
                if (String.IsNullOrEmpty(username))
                {
                    username = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;
                }
                if (String.IsNullOrEmpty(password))
                {
                    taskDefinition.Principal.UserId = username;
                    taskDefinition.Principal.LogonType = TaskLogonType.InteractiveToken;
                    task = taskService.RootFolder.RegisterTaskDefinition(
                        taskName,
                        taskDefinition,
                        TaskCreation.CreateOrUpdate,
                        username);
                }
                else
                {
                    taskDefinition.Principal.UserId = username;
                    taskDefinition.Principal.LogonType = TaskLogonType.Password;
                    task = taskService.RootFolder.RegisterTaskDefinition(
                        taskName,
                        taskDefinition,
                        TaskCreation.CreateOrUpdate,
                        username,
                        password);
                }
            }
            if (task != null && task.State == TaskState.Ready)
            {
                result = true;
                Console.WriteLine("任务创建成功！");
            }
            return result;
        }

        public static Microsoft.Win32.TaskScheduler.Task GetTask(string taskPath)
        {
            return new TaskService().GetTask(taskPath);
        }


        /// <summary>
        /// Deletes the test task.
        /// </summary>
        /// <param name="taskName">Name of the task.</param>
        public static void DeleteTask(string taskName)
        {
            TaskService ts = new TaskService();
            ts.RootFolder.DeleteTask(taskName);
        }
    }
}
